package net.xiangcaowuyu.simplemybatis.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * mybatis第一个配置文件
 * @author laughing
 * @date 2020/9/30
 * @site https://www.xiangcaowuyu.net
 */
@Configuration
@MapperScan(basePackages = {"net.xiangcaowuyu.simplemybatis.mapper.one"},sqlSessionFactoryRef = "sqlSessionFactoryOne",sqlSessionTemplateRef = "sqlSessionTemplateOne")
public class MyBatisConfigOne {

    private final Logger logger = LoggerFactory.getLogger(MyBatisConfigOne.class);

    @Resource(name = "dataSourceOne")
    DataSource dataSourceOne;

    @Bean
    SqlSessionFactory sqlSessionFactoryOne() {
        SqlSessionFactory sqlSessionFactory = null;
        try {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/one/*.xml"));
            sqlSessionFactoryBean.setDataSource(dataSourceOne);
            sqlSessionFactory = sqlSessionFactoryBean.getObject();
        }catch (Exception ex){
            logger.error(ex.getMessage());
        }
        return sqlSessionFactory;
    }

    @Bean
    SqlSessionTemplate sqlSessionTemplateOne(){
        return new SqlSessionTemplate(sqlSessionFactoryOne());
    }
}
